<?php

use GuzzleHttp\Client;
use Core\ResourceController;
use Models\Order;
use Models\Order_item;
use Models\Cart;
use Models\User;
use Models\UserLevel;
use Models\Evaluate;

class OrderController extends ResourceController
{
	public function create()
	{
		$items = $this->input->post('item_id');
		$qtys = $this->input->post('qty');
		if(!is_array($items)) $items = array_filter(explode(',', $items));
		if(!is_array($qtys)) $qtys = explode(',', $qtys);
		if (!$items) {
			return $this->validateError('请选择商品');
		}
		$i = 0;
		$data = array();

		foreach ($items as $it) {
			$data[] = array('item_id'=>$it,'qty'=>$qtys[$i]);
			$i++;
		}

		$order = new Order;
		$result = $order->create($data,$this->session->authUser['id']);
		if(!$result){
			$error = $order->error_info[$order->error];
			return $this->validateError($error);
		}

		Cart::where_in('item_id', $items)
			->where('user_id', $this->session->authUser['id'])
			->deleteAll();

		return $this->success($result);
	}

	public function index()
	{
		$order = new Order;
		if ($this->input->get('status') != -1 && $this->input->get('status') !== '' && $this->input->get('status') !== null) {
			$order->where('status', $this->input->get('status'));
			if ($this->input->get('status') == 3) {
				$order->where('comment', 0);
			}
		}

		$page = $order
			->where([
				'user_id' => $this->session->authUser['id'],
			])
			->order_by('id desc')
			->paginate(20)
			->to_array();

		$order_item = new Order_item;
		$order_items = [];
		$orders = arr_key($page['data']);
		if ($page['data']) {
			$order_ids = array_reduce($page['data'], function ($car, $item) {
				if(!$car) {
					$car = [];
				}
				$car[] = $item['id'];

				return $car;
			});
			$order_items = $order_item
				->where_in('order_id', $order_ids)
				->with([
					'product' => function ($model) {
						$model->select('id,title,en_title,thumbnail');
					},
					'item' => function ($model) {
						$model->select('id,title,en_title,price,solded');
					}
				])->get();
				//->with(['product', 'item'])->get();
			foreach ($order_items as $key => $value) {
				isset($orders[$value['order_id']]['items']) || $orders[$value['order_id']]['items'] = [];
				$orders[$value['order_id']]['items'][] = $value;
			}
		}
		$page['data'] = array_values($orders);

		return $this->success($page);
	}

	// 订单详情
	public function detail($id)
	{
		$order = new Order();
		if (!$order->find($id)) {
			return $this->notFoundResponse();
		}
		$order_items = Order_item::where('order_id', $order['id'])
			->with('product','id,title,en_title,thumbnail')
			->with('item','id,title,en_title,weight,price,solded')
			->get();
		$order['item'] = $order_items;

		$order['address'] = $order->address();

		$user = (new User)->find($this->session->authUser['id']);
		// 折扣
		$level = $user->level();
		$order['total'] = $order['total']*($level['discount'] ?: 1);

		return $this->success([
			'order' => $order,
			'user' => $user
		]);
	}

	// 取消订单
	public function cancel($id)
	{
		$order = new Order();
		if (!$order->find($id)) {
			return $this->notFoundResponse();
		}
		if ($order['user_id'] !== $this->session->authUser['id']) {
			return $this->forbiddenResponse();
		}
		if ($order['status'] != 0) {
			return $this->response(['error' => '该订单无法取消'], 422);
		}

		$order['status'] = 8;
		$order->update();

		return $this->success();
	}

	public function confirm($id)
	{
		$order = new Order();
		if (!$order->find($id)) {
			return $this->notFoundResponse();
		}
		if ($order['user_id'] !== $this->session->authUser['id']) {
			return $this->forbiddenResponse();
		}
		if (!in_array($order['status'], [1, 2, 4, 6, 7])) {
			return $this->response(['error' => '该订单无法确认收货'], 422);
		}

		$order['status'] = 3;
		$order->update();

		return $this->success();
	}

	public function evaluate ($id) {
		$order = new Order();
		if (!$order->find($id)) {
			return $this->notFoundResponse();
		}
		if ($order['user_id'] !== $this->session->authUser['id']) {
			return $this->forbiddenResponse();
		}
		if ($order['comment'] == 1) {
			return $this->response(['error' => '该订单已评价'], 422);
		}

		$this->load->library('form_validation');
		$this->form_validation->set_rules('star', '评分', 'required|less_than_equal_to[5]')
			->set_rules('content', '内容', 'trim|required');
		if (!$this->form_validation->run()) {
			return $this->validateError($this->form_validation->error_array());
		}
		$this->db->trans_start();
		$order_item = new Order_item;
		$order_items = $order_item->where('order_id', $order['id'])->get();
		foreach ($order_items as $key => $value) {
			$evaluate = new Evaluate();
			$evaluate->load([
				'order_Id' => $order['id'],
				'product_id' => $value['product_id'],
				'item_id' => $value['item_id'],
				'user_id' => $value['user_id'],
				'star' => $this->input->post('star'),
				'content' => $this->input->post('content'),
				'images' => $this->input->post('images')
			]);
			$evaluate->add();
		}
		$order['comment'] = 1;
		$order->update();
		$this->db->trans_complete();

		return $this->success();
	}

	public function delete($id)
	{
		$order = new Order();
		if (!$order->find($id)) {
			return $this->notFoundResponse();
		}
		if ($order['user_id'] !== $this->session->authUser['id']) {
			return $this->forbiddenResponse();
		}

		$order->delete();

		return $this->success();
	}

	public function refund($id)
	{
		$order = new Order();
		if (!$order->find($id)) {
			return $this->notFoundResponse();
		}
		if ($order['user_id'] !== $this->session->authUser['id']) {
			return $this->forbiddenResponse();
		}
		if ($order['status'] == 0 || $order['status'] == 10 || strtotime('+7 days '.$order['create_time']) > time()) {
			$order->update(null, [
				'status' => 10,
			]);

			return $this->response(['error' => '改订单已在退货中或超过退货期限'], 422);
		}
	}
}
